﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridObj : MonoBehaviour {
    private float m_fMoveSpeed = 6f;
    private Vector3 m_v3Dir = Vector3.zero;
    private GridNode m_pCenterNode;
    private bool m_bMoveing = false;
    private List<Vector3> path;
    private int pathIndex;
    private Vector3 nextPoint;
    private float stopTime;
    public void Init(Vector3 pos)
    {
        m_pCenterNode = GridMap.Instance.GetNodeByPos(pos);
        gameObject.transform.position = m_pCenterNode._worldPos;
        m_pCenterNode.AddItem(this);
        path = new List<Vector3>();
    }
    
    public void MoveTo(GridNode to)
    {
        m_bMoveing = true;
        path.Clear();
        GridNode node = GridMap.Instance.SearchPath(transform.position, to._worldPos);
        path.Add(node._worldPos);
        while (node._parent != null)
        {
            node = node._parent;
            path.Add(node._worldPos);
        }
        pathIndex = path.Count - 2;
        nextPoint = path[pathIndex];
        stopTime = Vector3.Distance(nextPoint, transform.position) / m_fMoveSpeed + Time.time;
        m_v3Dir = Vector3.Normalize(nextPoint - transform.position);
    }

    public void MoveTo(Vector3 pos)
    {
        GridNode node = GridMap.Instance.GetNodeByPos(pos);
        MoveTo(node);
    }

    private void Update()
    {
        if (m_bMoveing)
        {
            if(stopTime <= Time.time)
            {
                pathIndex--;
                if (pathIndex < 0)
                {
                    m_bMoveing = false;
                    transform.position = nextPoint;
                    ArriveNewNode();
                }
                else
                {
                    //到达了下一个路径点
                    ArriveNewNode();
                    nextPoint = path[pathIndex];
                    stopTime = Vector3.Distance(nextPoint, transform.position) / m_fMoveSpeed + Time.time;
                    m_v3Dir = Vector3.Normalize(nextPoint - transform.position);
                }
            }
            else
            {
                transform.position = transform.position + m_v3Dir * m_fMoveSpeed * Time.deltaTime;
            }
        }
    }

    private void ArriveNewNode()
    {
        m_pCenterNode.Clean(this);
        m_pCenterNode = GridMap.Instance.GetNodeByPos(transform.position);
        m_pCenterNode.AddItem(this);
    }
}
